package com.one.apartmentsystem.common.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 邮件发送示例类，使用JavaMail API发送邮件。
 */

public class SendMailUtil {

    public static void sendMail(String phone,String code)   {
        try {

            // 配置邮件发送的属性
            Properties prop = new Properties();
            prop.setProperty("mail.host", "smtp.qq.com");
            prop.setProperty("mail.transport.protocol", "smtp");
            prop.setProperty("mail.smtp.auth", "true");

            // 设置QQ邮箱的SSL加密配置
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);

            // 创建邮件会话对象，并配置认证信息
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1613828539@qq.com", "xgoxctxpsdzmijje");
                }
            });

            // 开启调试模式，以便查看发送过程的详细信息
            session.setDebug(true);

            // 获取传输对象
            Transport ts = session.getTransport();

            // 连接邮件服务器
            ts.connect("smtp.qq.com", "1613828539@qq.com", "xgoxctxpsdzmijje");

            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            // 设置发件人、收件人、主题和内容
            message.setFrom(new InternetAddress("1613828539@qq.com"));

            message.setRecipient(Message.RecipientType.TO, new InternetAddress(phone));

            message.setSubject("");

            //生成4为随机数

            message.setContent(
                    "您的验证码是：" + code + "，请勿泄露。","text/html;charset=UTF-8");

            // 发送邮件

            ts.sendMessage(message, message.getAllRecipients());

            // 关闭连接

            ts.close();
        } catch (MessagingException | GeneralSecurityException e) {
            throw new RuntimeException(e);
        }

    }
}
